package com.basker.pisces.core.query.factory;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.basker.pisces.core.query.QueryInfo;
import com.basker.pisces.core.query.builder.QueryBuilder;
import com.basker.pisces.core.query.meta.QueryMeta;

@Component
class SimpleQueryInfoFactory extends QueryInfoFactory<SimpleQueryInfo> {

    @Override
    public QueryInfo create(QueryMeta queryMeta, SimpleQueryInfo simpleQueryInfo) {
        QueryBuilder builder = QueryBuilder.create(queryMeta);

        builder.setSelectReferenceFields(simpleQueryInfo.isSelectReferenceFields());

        this.addSelectFields(simpleQueryInfo.getSelectFields(), builder);
        this.addConditions(simpleQueryInfo.getConditions(), builder);
        this.addOrders(simpleQueryInfo.getOrders(), builder);

        return builder.buildQueryInfo();
    }

    protected void addSelectFields(List<String> selectFields, QueryBuilder builder) {
        if (!CollectionUtils.isEmpty(selectFields)) {
            builder.select(selectFields.toArray(new String[selectFields.size()]));
        } else {
            builder.selectMainTableFields();
        }
    }

}
